package com.springboot.demo.interceptor;

import com.springboot.demo.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SessionHandlerInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{

        User user = (User)request.getSession().getAttribute("user");
        if(user == null){
            //如果没有登录，重定向到login.html
            response.sendRedirect("/login.html");
            return false;
        }
        return true;
    }

    public void postHandler(HttpServletRequest request, HttpServletResponse response,
                            Object handler, ModelAndView modelAndView) throws Exception{
        //Controller方法处理完毕后，调用此方法

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex){
        //页面渲染完毕后调用此方法，通常用来清楚某些资源，类似于Java语法的finall

    }
}
